layui.config({base: top.basePath+'/static/common/layui/js/'})
    .define(['layer','laytpl','newLayer','newDate','element'], function(exports) {
	"use strict";

	var $ = layui.jquery,laytpl=layui.laytpl, element ;

	try{
        element= layui.element();
    }catch (e){
	    element=layui.element;
    }


	var TableKit = function () {
		this.config={
            elem: undefined, //存放begtable的窗口，必填
            tableName: undefined,
            cols: undefined, // 数据列
            url: undefined, //远程地址
            height:'full-150',
            checked: false, //显示多选按钮
            done: undefined, //Function	数据渲染完的回调。你可以借此做一些其它的操作
            page: true, //启用分页功能
            limit:20,
            limits:[10,20,50,100],
            loading:true,
            rowHeight:31,
            id:undefined,//设定容器唯一ID
            isMulti:false//当前复选状态是否是多选
		}
    }

    /**
     * 设置 table的 初始配置数据
     * @param options
     * @returns {*}
     */
    TableKit.prototype.doConfig= function(options) {
        var that = this;
        $.extend(true, options, that.config);
        options.tableName=options.elem.replace('#','');
        return options
    }

    /**
     * 通用的列属性 转换
     * @param that
     */
    TableKit.prototype.doWithCols= function(that) {
        var hasImg=false,cols=that.config.cols;
        //取第一个`
        for(var i in cols[0]){
            var col=cols[0][i];

            //列属性
            if(col.field){
                // ================ check field atrribute======================
                if(col.field==='sex'){col.templet= function(r) {return r.sex==1 ? "男" : "女"}}

                if(col.field.endsWith('Url')||col.field.endsWith('url')){
                    col.templet= function(r) {return r[col.field] ? '<img src="'+r[col.field]+'?x-oss-process=image/resize,w_120"></img>' : "" ;}
                    hasImg=true;
                }

                if(col.field==='remark'){col.type= col.type||'textarea'; col.edit=false}

                if(col.field.endsWith('Url') || col.field ==='code' || col.field.endsWith('Code')
                    ||col.field.endsWith('Time') || col.field ==='time'){col.width= (col.width||0)>190 ? col.width : 190  }
                if(col.field.endsWith('Phone') || col.field ==='phone'
                    ||col.field.endsWith('Tel') || col.field ==='tel'){col.width= (col.width||0)>140 ? col.width : 140  }


                // ================ check type atrribute======================

                // boolean 值
                if(col.type==='boolean'){col.templet= function(r) {return r[col.field] == '1' ? "是" : '否' }}

                if(that.config.openColEdit && col.type==='textarea'){
                    col.templet= function(r) {
                        var colValue = r[col.field]|| '暂无备注';

                        return '<a style="color: #44b3f3;" '
                                    +'onclick="window.layui.newTable.openEditLayerWithFieldsThenCall(\''+col.title+'\','
                                        + '[{text:\''+col.title+'\',type:\'textarea\',name:\''+col.field+'\',value:\''+colValue+'\'}],'
                                        +'function (formData){formData.id=\''+r.id+'\';layui.newAjax.post(\''+that.querys.editUrl.replace("edit","saveOrUpdate")+'\',formData);});" '
                                        +'title="点击查看/修改'+colValue+'">'
                                  +colValue
                                +'</a>'
                    }
                }

                // ================ check other atrribute======================
                // a标签 携带参数 跳转 tab
                if(col.jumpTo){
                    col.templet= function(r) {
                        var colValue = r[col.field];
                        return '<a onclick="jumpTo(\''+col.jumpTo.title+'\',\''+col.jumpTo.paramUrl+colValue
                            +'\');" style="color: cornflowerblue;border-bottom-style: groove;" title="点击查看'+col.jumpTo.title+'">'+colValue+'</a>'}
                }
                if(col.data){col.templet= function(r){return col.data[r[col.field]]} }
                //可修改 变色
                if(col.edit){col.style='color: #44b3f3;';}

                col.width = (col.width || 100);
            }


        }
        if(hasImg){
            that.config.rowHeight= that.config.rowHeight<75 ? 75 : that.config.rowHeight;
        }
        return hasImg;
    }

    /**
     * 设置查询区 展示的初始配置数据
     * @param that
     * @param querys
     */
    TableKit.prototype.doQuery = function(that,querys) {
        $.extend(true, that.querys, querys);
        // 不添加常用的按件
        if(!querys.notUseCommonButton){
            that.querys.noRowButtons.push({id:'add',text:'新增'});
            that.querys.buttons.unshift({id:'edit',text:'编辑/查看'});
            that.querys.multiButtons.push({id:'del',class:'layui-btn-warm',text:'删除'});
        }
    };

    /**
     * 开始渲染表格
     * @param that
     * @param options
     */
    TableKit.prototype.doRender=function(that,options){
        $.extend(true, that.config, options);

        //渲染查询框
        if(that.needQuery){
            if(!that.querys.elem){
                that.querys.elem=that.config.elem;
            }
            renderQuery(that.querys);
        }

        var hasImg=this.doWithCols(that);

        that.config.where=JSON.parse(this.getFormParams(that.querys.elem+'_form'));

        // 有图片的表格，body行高改为75px
        var doneF=that.config.done;
        that.config.done=function(){
            $('.layui-table-body').find('.layui-table-cell').each(function(index,div){
                $(div).height(that.config.rowHeight).css('line-height',that.config.rowHeight+'px');
                //console.log($(div))
            })
            if(doneF){doneF();}
        }

        that.target.render(that.config);

        bindButtonFunction(that.querys.noRowButtons);
        bindButtonFunction(that.querys.buttons);
        bindButtonFunction(that.querys.multiButtons);
    }

    function bindButtonFunction(bs) {
        if(bs && bs.length>0){
            for(var i in bs){
                $("#"+bs[i].id).on('click',function(ele){
                    if(bs[i].function)bs[i].function(ele);
                });
            }
        }
    }

    /** 渲染查询区域内容  */
    function renderQuery(querys) {
        var id=querys.elem.substr(1);
        var queryHtml='<fieldset><legend><a>'+querys.title+'</a></legend>'
            +'<form id="'+ id+'_form">'+renderConditions(querys.conditions)+'</form>'
            +renderHelpButtons(id,querys.noRowButtons)
            +renderOneRowButtons(id, querys.buttons)
            +renderMultiRowButtons(id, querys.multiButtons)
            +'</fieldset>';

        $(querys.elem).html(queryHtml);
        element.init();
    }

    /** 渲染所有的查询条件表单 */
    function renderConditions(conditions) {
        var condHtml='';
        if(conditions){
            for (var i in conditions){
                if(conditions[i]){
                    var ele=conditions[i];
                    ele.value=ele.value||"";
                    condHtml+=('<div style="margin-bottom: 10px;margin-right: 10px" class="layui-inline">'+renderCondKit[ele['type'] || 'input'].call(this,ele)+'</div>')
                }
            }
        }
        return condHtml;
    }

    /** 查询框渲染工具类 */
    var renderCondKit={
        'input' : function(ele){
            return laytpl('<input type="text" name="{{d.name}}" placeholder="{{d.text}}" value="{{d.value}}" class="layui-input">')
                .render(ele);
        }, 'select':function (ele) {
            var selectHtml='<select style="display: inline" name="'+ele['name']+'"><option value="">选择'+ele.text+'</option>';
            var options=ele['data'] || {"1":"是","0":"否"};
            for(var key in options){
                selectHtml += '<option value="'+key+'" '+ (ele.value==key ? 'selected' : '') +'>'+ele.text+'->'+options[key]+'</option>';
            }
            selectHtml += '</select>'
            return selectHtml;
        },'date':function (ele) {
            $('body').on('click', 'input[name='+ele.name+']', function(){
                var input=$(this);
                layui.newDate.render({
                    elem: 'input[name='+ele.name+']'
                    ,range: true
                });
            })
            return '<input type="text" name="'+ele.name+'" class="layui-input" placeholder="'+ele.text+'">';
        },'day':function (ele) {
            $('body').on('click', 'input[name='+ele.name+']', function(){
                var input=$(this);
                layui.newDate.render({
                    elem: 'input[name='+ele.name+']'
                    ,range: false
                });
            })
            return '<input type="text" name="'+ele.name+'" class="layui-input" placeholder="'+ele.text+'">';
        },'hidden':function (ele) {
            return '<input type="hidden" name="'+ele.name+'" value="'+ele.value+'">';
        },'code':function (ele) {
            var codeHtml=renderCondKit.hidden(ele);
            codeHtml += '<input type="text" name="'+ele.name+'Name" placeholder="选择'+ele.text+'" value="'+ele.value+'" class="layui-input">'
            $('body').on('click', 'input[name='+ele.name+'Name]', function(){
                var input=$(this);
                layui.newLayer.open({
                    title: '选择'+ele.text,
                    content: ele.url,
                    btn:['选择'],
                    yes:function (index,openLayer) {
                        var row=openLayer.find("iframe")[0].contentWindow.layui['newTable'].getSelectedRows(true);
                        if(!row)return;
                        $('input[name='+ele.name+']').val(row.code||row.name);
                        $('input[name='+ele.name+'Name]').val(row.name);

                        layui.newLayer.close(index);
                    }
                });
            })
            return codeHtml;
        },'textarea':function (ele) {
            return '<textarea name="'+ele.name+'" placeholder="'+(ele.placeholder||'请输入内容')+'" class="layui-textarea">'+ele.value+'</textarea>';
        }
    }

    /** 辅助功能按钮， 单选，多选切换 */
    function renderHelpButtons(pref,noRowButtons) {
        $('body').on('click', '#clear', function(){
           $('form').get(0).reset();
            $('form input').val('');
        });

        var html='<div class="layui-btn-group" style="float: left;">'
            +'<button id="clear" class="layui-btn">清空</button>'
            +'<button id="'+pref+'_search" class="layui-btn">查询</button>';

        if(noRowButtons && noRowButtons.length>0){
            for(var i in noRowButtons)
                html += renderButton(pref,noRowButtons[i],i);
        }

        html += ('</div>'
                +'<div class="layui-btn-group" style="float: left;">'
                     +'<button id="change_choose_type" class="layui-btn" style="display: none">使用多选</button>'
                +'</div>');
        return html;
    }

    /** 普通的业务操作 */
    function renderOneRowButtons(pref, buttons) {
        var searchButton='<div class="layui-btn-group" style="float: left;">';

        if(buttons && buttons.length>0){
            for(var i in buttons){
                searchButton += renderButton(pref,buttons[i],i);
            }
        }
        searchButton += '</div>';
        return searchButton;
    }

    function renderButton(pref,button,index){
        if(!button.id)button.id=(pref+"_button_"+index);
        return laytpl('<button id="{{d.id}}" class="layui-btn">{{d.text}}</button>').render(button)
    }

    /** 批量操作 */
    function renderMultiRowButtons(id, buttons) {
        var searchButton='<div class="layui-btn-group" style="float: left;">\
                            <ul class="layui-nav" style="padding:0 0 0 0 ">\
                                <li class="layui-nav-item">\
                                    <a class="layui-btn layui-btn-normal" href="javascript:;">批量功能</a>\
                                    <dl class="layui-nav-child layui-btn">' ;

        if(buttons && buttons.length>0){
            for(var i in buttons){
                if(!buttons[i].class)buttons[i].class='layui-bg-green';
                if(!buttons[i].id)buttons[i].id=(id+"_multi_button_"+i);
                searchButton += laytpl('<dd><a href="javascript:;" id="{{d.id}}" class="layui-btn {{d.class}}">{{d.text}}</a></dd>').render(buttons[i]);
            }
        }
        searchButton += '</dl></li></ul></div>';
        return searchButton;
    }

    //======================功能区================
    /** 获取表格中选中的数据行 */
    TableKit.prototype.doGetSelectedRows=function (that,needSingle) {
        var checkStatus = that.target.checkStatus(that.config.id);
        var size=checkStatus.data.length;
        if(size === 0 ){
            msgErrorTips("请先选中数据行！");
            return;
        }
        if(needSingle && size>1){
            msgErrorTips("只能选择一行！");
            return;
        }else {
            return needSingle ? checkStatus.data[0] : checkStatus.data;
        }
    }

    TableKit.prototype.doCallWhenSelectRows=function (that,needSingle,cb) {
        var result = this.doGetSelectedRows(that,needSingle);
        // 有效对象 并且 （是对象或数组或字符串）
        if(result && (result.length>0||result.id>0))cb(result);
    }

    /** 获取选择的行的id数组 */
    TableKit.prototype.doGetSelectedRowIds = function(that) {
        var rows = this.doGetSelectedRows(that,false);
        var ids=[];
        for (var i in rows){
            ids.push(rows[i].id);
        }
        return ids
    };

    TableKit.prototype.doCallWhenSelectRowIds = function(that, cb) {
        var result = this.doGetSelectedRowIds(that);
        if(result && (result.length>0||result.id>0))cb(result);
    };

    /** 获取查询区域的参数 */
    TableKit.prototype.getFormParams=function getFormParams(formId){
        var params = $(formId).serializeArray();
        var values = {};
        for(var x in params ){
            values[params[x].name] = params[x].value;
        }
        var idata = JSON.stringify(values)
        return idata;
    }

    /** 弹窗 编辑，确定后回调
     *  fieldArray 参照 conditions 中的 item*/
    TableKit.prototype.doOpenEditLayerWithFieldsThenCall=function (that, title, fieldArray, cb) {
        var kit=this;
        // 填充 需要修改的字段
        var condHtml='';
        for (var i in fieldArray){
            if(fieldArray[i]){
                var ele=fieldArray[i];
                ele.value=ele.value||"";
                condHtml+=('<div class="layui-row layui-col-space12"><div class="layui-col-md10">'+
                                '<label class="layui-form-label">'+ele['text']+'</label>'+
                                '<div class="layui-input-block" style="margin-top:15px;margin-right:30px">'+
                                    renderCondKit[ele['type'] || 'input'].call(this,ele)+
                            '</div></div></div>')
            }
        }

        layui.newLayer.open({
            title: title,
            type:1,
            content: '<form class="layui-form"  id="openEditLayer">'+condHtml+'</form>',
            btn:['提交','取消'],
            area:['70%', '65%'],
            yes:function (index,openLayer) {
                var loadIndex=layui.newLayer.load(2);
                Promise.all(cb(JSON.parse(kit.getFormParams(openLayer.find('#openEditLayer')))))
                    .then(layui.newLayer.close(loadIndex))
                    .then(layui.newLayer.close(index));
            }
        });

    }

    /** 查询按钮功能，并绑定回车事件 */
    TableKit.prototype.doBindSearch= function (that) {
        var kit=this;
        $(that.querys.elem+'_search').on('click', function(){
            that.refreshTable(JSON.parse(kit.getFormParams(that.querys.elem+'_form')));
        });
        $(document).keyup(function(event){
            /**绑定页面的回车事件，触发查询按钮的点击*/
            if(event.keyCode ==13){
                $(that.querys.elem+'_search').trigger('click');
            }
        });
    }

    TableKit.prototype.doSearch= function (that) {
        $(that.querys.elem+'_search').trigger('click');
    }
    TableKit.prototype.doClear= function (that) {
        $('#clear').trigger('click');
    }



    /** 常规的 增删改 功能 实现逻辑 */
    TableKit.prototype.doBindModifyFunction= function (that) {
        // 弹窗新增
        $('#add').on('click',function(){
            that.openNewLayer('新增'+that.querys.name,that.querys.editUrl);
        });
        // 弹窗修改
        $('#edit').on('click',function(){
            that.callWhenSelectOneRow(function (row) {
                var url=that.querys.editUrl.indexOf("?")>0 ? (that.querys.editUrl+"&id="+row.id) : ((that.querys.editUrl+"?id="+row.id))
                that.openNewLayer('编辑'+that.querys.name,url);
            })
        })

        doBindColEidt(that);


        //当前窗口删除
        $('#del').on('click', function() {
            that.callWhenSelectRowIds( function(ids) {
                layui.newLayer.confirm("是否确定删除！", function() {
                    $.post(that.querys.editUrl.replace("edit","del"),{id:ids}, function(result) {
                        if(result.code==0) {
                            that.refreshTable();
                            layui.newLayer.msg("删除成功！")
                        }else {
                            layui.newLayer.alert(result.message);
                        }
                    })
                })
            })
        })
    }

    /** 开启符合选择模式， that.config.isMulti true，多选， false 单选 */
    TableKit.prototype.doOpenMixChooseType=function (that) {
        $('#change_choose_type').show().on('click',function(obj){
            var $this=$(this);
            that.config.isMulti = !that.config.isMulti;
            $this.html(that.config.isMulti?'使用单选':'使用多选');
        });

        that.target.on('checkbox('+that.config.tableName+')', function(obj){
            if(!that.config.isMulti && obj.type=='one' && obj.checked && !that.config.isCkTrigRuning){//如果触发的是全选，则为：all，如果触发的是单选，则为：one
                that.config.isCkTrigRuning=true;
                var fixCheckBoxUi=$('div.layui-table-fixed>.layui-table-body');
                //fixCheckBoxUi.find('.layui-unselect .layui-form-checkbox. layui-form-checked').trigger('click');
                fixCheckBoxUi.find('.layui-unselect .layui-form-checkbox').eq(obj.data.LAY_TABLE_INDEX).trigger('click');
                that.config.isCkTrigRuning=false;
            }
        });

        return that;
    }

    /** 打开新的图层 */
    TableKit.prototype.doOpenNewLayer=function (title,url) {
        layui.newLayer.open({
            title: title,
            content: url,
        });
    }

    function msgErrorTips(msg) {
        layui.newLayer.msg(msg, {
            icon: 5
        });
        return;
    }

    /** 是否开启列编辑 */
    function doBindColEidt(that) {
        if(!that.config.openColEdit)return;

        // 当前窗口修改 在 列属性中增加 edit:true 生效
        that.target.on('edit('+that.config.elem.replace('#','')+')',function (obj) {
            if(that.querys.editCallBack){
                that.querys.editCallBack(obj.data,this);
            }
            var field=obj.field;//当前编辑的字段名
            var data={"id":obj.data.id};
            data[field]=obj.value;
            var loadIndex=layui.newLayer.load(2);
            layui.newAjax.post(that.querys.editUrl.replace("edit","saveOrUpdate"),data,
                function (result) {
                    layui.newLayer.msg( "更新成功！");
                },function (message) {
                    layui.newLayer.alert(message);
                },function(){
                    layui.newLayer.close(loadIndex)
                })
        })
    }

	exports('tableKit', new TableKit());
});

function jumpTo(title, paramUrl) {
    top.tab.config.jumpTo(title,paramUrl);
}

function getRowsCode(rows) {
    return getRowsField(rows, 'code');
}
function getRowsField(rows,field) {
    var codes=[];
    for(var i in rows){
        codes.push(rows[i][field])
    }
    return codes;
}

function closeCurrentLayer() {
    parent.layer.close(parent.layer.getFrameIndex(window.name));
}
function alert(msg) {
    parent.layer.msg(msg);
}

/**
 * 数组元素交换位置,如果交换了，则返回true
 * @param {array} arr 数组
 * @param {number} index1
 * @param {number} index2
 * index1和index2分别是两个数组的索引值，即是两个要交换元素位置的索引值，如1，5就是数组中下标为1和5的两个元素交换位置
 */
function swapArray(arr, sourceIndex, targetIndex) {
    var len=arr.length;
    if(sourceIndex<0) sourceIndex = sourceIndex+len;
    if(targetIndex<0) targetIndex = targetIndex+len;

    if(sourceIndex>(len-1) || targetIndex>(len-1)){
        alert("不能超出最大长度范围！");
        return false;
    }
    if(sourceIndex === targetIndex){
        alert("目标位置和当前位置一致，无需移动！");
        return false;
    }

    arr[sourceIndex] = arr.splice(targetIndex, 1, arr[sourceIndex])[0];
    return true;
}